package com.ley.springboot.aop.aspect;

import com.ley.springboot.aop.annotation.NeedLogin;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 用于登录拦截的切面,如果用户没有登录,不能访问(AOP只能拦截到方法级)
 **/
@Aspect
@Component
@Slf4j
@Order(1)
public class LoginAspect {


    /**
     * 扫描所以带有特定注解的类方法
     */
    @Pointcut(value = "@annotation(com.ley.springboot.aop.annotation.NeedLogin)")
    private void loginPointcut() {
    }


    @Around(value = "loginPointcut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = "need login.";

        //获取拦截的方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        //如果类上没有NeedLogin注解,判断方法
        Method targetMethod = methodSignature.getMethod();
        NeedLogin methodNeedLoginAnnotation = targetMethod.getAnnotation(NeedLogin.class);
        boolean value = methodNeedLoginAnnotation.value();
        if (!value) {
            result = joinPoint.proceed();
            log.info("result: {}", result);
        }
        return result;
    }

}
